package com.sherry.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sherry.model.Fruit;
import com.sherry.service.IFruitService;
import com.sherry.service.impl.FruitServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/fruit/list")
public class GetFruitServlet extends HttpServlet {
    // 处理post请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("接收到前端POST请求");
//        返回的fruitList的中文乱码都是??,因为没加这个
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

//        接收前端参数
        String fname= request.getParameter("fname");
        Integer pageIndex= Integer.parseInt(request.getParameter("pageIndex"));

//        获取业务层对象并调用其方法，及传递前端参数给业务层
        IFruitService fruitService=new FruitServiceImpl();
        List<Fruit> fruitList =fruitService.getFruitList(fname,pageIndex);
//        int totalPage=fruitService.totalPage(fname);  自己版
        Integer totalPage=fruitService.getTotalPage(fname);
        System.out.println("fruitList: " + fruitList);
        System.out.println("查询到的数据: " + fruitList.size());


        JSONObject data=new JSONObject();
        data.put("fruitList",fruitList);
        data.put("totalPage",totalPage);
        // 创建配置并设置日期格式
        String dataStr = JSON.toJSONString(data, SerializerFeature.WriteDateUseDateFormat);

        PrintWriter write = response.getWriter();
        write.write(dataStr);
        write.flush();
    }

    // 处理get请求
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("接收到前端GET请求");
        doPost(request, response);
    }
}